package crp.core.space.domain.services;

import com.qwlabs.lang.C2;
import com.qwlabs.tree.Tree;
import crp.core.space.domain.models.LocationEntity;
import crp.core.space.domain.repositories.LocationRepository;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.Collection;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Stream;


@ApplicationScoped
public class LocationSearcher {
    private final LocationRepository locationRepository;

    @Inject
    public LocationSearcher(LocationRepository locationRepository) {
        this.locationRepository = locationRepository;
    }

    public Stream<LocationEntity> findOffspring(Collection<String> locationIds) {
        if (C2.isEmpty(locationIds)) {
            return Stream.empty();
        }
        Tree<LocationEntity> tree = Tree.toTree(locationRepository.findAll().list(), LocationEntity::getId, LocationEntity::getParentId);
        return locationIds.stream()
                .map(locationId -> tree.findNode(location -> location.getId().equals(locationId)).orElse(null))
                .filter(Objects::nonNull)
                .flatMap(node -> node.mapDeep(Function.identity()).stream());
    }

    public Stream<LocationEntity> findByIds(Set<String> ids) {
        return locationRepository.findByIds(ids);
    }

    public Stream<LocationEntity> root() {
        return locationRepository.findRoot();
    }

    public Stream<LocationEntity> findAll() {
        return locationRepository.findAll().stream();
    }
}
